import React, {Component} from 'react'
import {Button, Form, Jumbotron} from 'react-bootstrap'
import {login, getProfile} from './utils';

class Login extends Component {
    state = {
        username: '',
        password: '',
        token: null
    }

    async onLogin(event) {
        await event.preventDefault()
        let token = await login(this.state.username, this.state.password)
        await this.setState({token: token})
        let user = await getProfile(token);
        await this.props.setState({user: user, token: token})
    }

    render() {
        console.log(this.props.state)
        return (this.props.state.user === null) ? (
            <Jumbotron>
                <Form onSubmit={this.onLogin.bind(this)} action={null}>
                    <Form.Group controlId="formUsername">
                        <Form.Label>用户名</Form.Label>
                        <Form.Control type="text"
                                      placeholder="输入用户名"
                                      value={this.state.username}
                                      onChange={(event) => this.setState({username:event.target.value})} />
                    </Form.Group>
                    <Form.Group controlId="formPassword">
                        <Form.Label>密码</Form.Label>
                        <Form.Control type="password"
                                      placeholder="输入密码"
                                      value={this.state.password}
                                      onChange={(event) => this.setState({password:event.target.value})} />
                    </Form.Group>
                    <Button variant="primary" type="submit">
                        登录
                    </Button>
                </Form>
            </Jumbotron>
        ) : (
            <Jumbotron>
                <h1>欢迎用户{this.props.state.user.name}!</h1>
                <p>
                    <Button variant="primary" onClick={() => {
                        this.setState({
                            username: '',
                            password: '',
                            token:null
                        })
                        this.props.setState({user: null})
                    }}>退出登录</Button>
                </p>
            </Jumbotron>
        )
    }
}

export {Login}